<?php
	//if (!isset($_SESSION)) { session_start(); }
  // Datos extraidos
  $lenguaje = 'es';
  //Archivos incluidos despues de la verficacion por seguridad.
  include_once('../../includes/fk_php/Connections/connection.php');
  
  switch($lenguaje): // Selecion de lenguaje de la apliacion
	case 'es': include_once('../../includes/fk_php/lenguaje_es(v2).php'); $DB_lenguaje = 'nom_es';
		break;
	case 'en': $DB_lenguaje = 'nom_en'; break;
  endswitch;

?>

<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <style type="text/css">
		.add {
            background-image:url(../../fk_skin/add.gif) !important;
        }
        .remove {
            background-image:url(../../fk_skin/delete.gif) !important;
        }
		.buscar {
            background-image:url(../../fk_skin/buscar.gif) !important;
        }
		.refresh {
            background-image:url(../../fk_skin/refresh.png) !important;
        }
	</style>
  <link rel="stylesheet" type="text/css" href="../../includes/extjs/resources/css/ext-all.css" />
  <!-- LIBS -->
  <script type="text/javascript" src="../../includes/extjs/adapter/ext/ext-base.js"></script>
  <!-- ENDLIBS -->
  <script type="text/javascript" src="../../includes/extjs/ext-all.js"></script>
  <!--	EDITOR GRID --->
  <script type="text/javascript" src="../../includes/extjs/src/widgets/grid/EditorGrid.js"></script>
  
  <script type="text/javascript" src="../../includes/extjs/src/locale/ext-lang-<?=$lenguaje?>.js"></script>
  <script type="text/javascript">
//-------------------------------------------------------    
	Ext.onReady(function(){
		Ext.BLANK_IMAGE_URL = '../../includes/extjs/resources/images/default/s.gif';
		Ext.QuickTips.init(); 
		Ext.form.Field.prototype.msgTarget = 'side';
		//Funcionalidad de Boton de busqueda
		
		
	//Arreglo bidimensional de datos 
	var storegrid = new Ext.data.JsonStore({ // asignandole a la propiedad json la data
		url: 'mod_user_grid.php',  
		root: 'data',
		fields: ['nomdirector','idcentro','nomcentro','url','activo','pais']
	});  
	storegrid.load({params:{buscar:'todos'}});
	
//-------------------------------------------------------

var store_perfiles= new Ext.data.JsonStore({  
			url:'perfiles_store.php',  
			root: 'data',  
			totalProperty: 'total',  
			fields: [  
				{name:'Idmenu', type: 'string'},  
				{name:'Nombremenu', type: 'string'}
			]  
		});
		store_perfiles.load();
		
		
var store_paises= new Ext.data.JsonStore({  
			url:'paises_store.php',  
			root: 'data',  
			totalProperty: 'total',  
			fields: [  
				{name:'Idmenu', type: 'string'},  
				{name:'Nombremenu', type: 'string'}
			]  
		});
		store_paises.load();
		
		
	var mySelectionModel = new Ext.grid.CheckboxSelectionModel({singleSelect: false});
	
	function renderFecha(value){
		return Ext.util.Format.date(value, 'Y-m-d');
	}
	
	// CREACION DEL GRID ===============================
	var gridcentros = new Ext.grid.EditorGridPanel({//new Ext.grid.GridPanel({ //Creando el objeto Ext.grid.GridPanel
		renderTo: 'grid-div',
		store: storegrid,
		title: '<?=TITLE_MACE_15?>',
		collapsible: true,
		frame: true,
		width:  '100%',
		clicksToEdit: 2,
		viewConfig: {forceFit: true},
		height: 600,
		stripeRows: true,
		autoScroll: true,
		border: false,
		loadMask: true,
		sm: mySelectionModel, //referencia al selectionModel
		columns: [
			new Ext.grid.CheckboxSelectionModel(),  
			{
				id			: 'idcentro',
				dataIndex	: 'idcentro',
				header		: '<?=TitleAdmin_039?>',
				width		: 100,
				sortable	: true
			},{
				id			: 'nomcentro',
				dataIndex	: 'nomcentro',
				header		: '<?=TitleAdmin_040?>',
				width		: 150,
				sortable	: true,
				editor		: {
							xtype: 'textfield',
							allowBlank: false
						}
			},{
				dataIndex	: 'url',
				header		: '<?=TitleAdmin_041?>',
				width		: 150,
				sortable	: true,
			    editor: new Ext.form.ComboBox({
						hiddenName  : 'centroId',  
						name        : 'centro_red',  
						width       : 190,  
						typeAhead: true,
						mode: 'remote',
						triggerAction: 'all',
						selectOnFocus:true,
						displayField: 'Nombremenu',  
						valueField  : 'Idmenu',
						store		: store_perfiles
				})
			},{
				dataIndex	: 'nomdirector',
				header		: '<?=TitleAdmin_042?>',
				width		: 150,
				sortable	: true,
				locked		: true,
				editor:new Ext.form.DateField({format :'d/m/Y'}) 
			},
			{
				dataIndex	: 'activo',
				header		: '<?=TitleAdmin_043?>',
				width		: 100,
				sortable	: true,
			    editor: new Ext.form.ComboBox({
						hiddenName  : 'centroId',  
						name        : 'centro_red',  
						width       : 190,  
						typeAhead: true,
						mode: 'local',
						triggerAction: 'all',
						selectOnFocus:true,
						displayField: 'Nombremenu',  
						valueField  : 'Idmenu',
						store		: new Ext.data.SimpleStore({
							fields: ['Idmenu', 'Nombremenu'],
							data : [['A','ACTIVO'],['D','DESACTIVO']]
						})
				})
			},
			{
				dataIndex	: 'pais',
				header		: 'Pais',
				width		: 100,
				sortable	: true,
				editor		: new Ext.form.ComboBox({
						hiddenName  : 'centroId',  
						name        : 'centro_red',  
						width       : 190,  
						typeAhead: true,
						mode: 'remote',
						triggerAction: 'all',
						selectOnFocus:true,
						displayField: 'Nombremenu',  
						valueField  : 'Idmenu',
						store		: store_paises
				})
			},
			{
				dataIndex	: 'pass',
				header		: 'Nuevo Password',
				width		: 150,
				sortable	: true,
				locked		: true,
				editor		: {
							xtype: 'textfield',
							allowBlank: false,
							inputType: 'password'
						}
			}
			],tbar: [
			'->',
                 {
                    text: 'Agregar',
                    tooltip: 'Click para agregar un usuario',
					iconCls:'add',
                    handler: agregarnuevouser //what happens when user clicks on it
                }, 
				'-',
				{
                    text: 'Borrar',
                    tooltip: 'Click para eliminarlo',
                    handler: borrar,
                    iconCls:'remove'
                },
				'-',
				{
                    text: 'Buscar',
                    tooltip: 'Click para buscar',
                    handler: buscar,
                    iconCls:'buscar'
                },'-',
				{
                    text: 'Actualizar',
                    tooltip: 'Click para buscar',
                    handler: function(){
						storegrid.reload({params:{buscar:'todos'}});
					},
                    iconCls:'refresh'
                }
            ]
	});
	//
	//----------------------------------------
	
		function saveSubmenu(oGrid_event){
				Ext.Ajax.request({   
			  waitMsg: 'Please wait...',
			  url: 'edit-usuarios.php',
			  params: {
				 idcentro: oGrid_event.record.data.idcentro,
				 nomcentro: oGrid_event.record.data.nomcentro,
				 url: oGrid_event.record.data.url,
				 nomdirector:oGrid_event.record.data.nomdirector,//.format("Y-m-d"),
				 activo:oGrid_event.record.data.activo,
				 pais:oGrid_event.record.data.pais,
				 pass:oGrid_event.record.data.pass
			  }, 
			  success: function(response){							
				 var result=eval(response.responseText);
				 switch(result){
				 case 1:
					storegrid.commitChanges();
					storegrid.reload();
					break;					
				 default:
					Ext.MessageBox.alert('Uh uh...','NO se pudo actualizar');
					storegrid.reload();
					break;
				 }
			  },
			  failure: function(response){
				 var result=response.responseText;
				 Ext.MessageBox.alert('error','No se pudo actualizar, algun error con la base');		
			  }									    
		   });
	}
	gridcentros.on({ 
		'afteredit': { 
			fn: function(oGrid_event){
				saveSubmenu(oGrid_event);
			}
		},
		'click': 	{
				fn: function(){
					var js_acces = 0;
					var selections = this.selModel.getSelections();
					Ext.each(selections,function(record){ 
						js_acces = 1; 
					});
					if (js_acces == 1){ 
						//document.getElementById('button_borrar').disabled = false; 
					}
					else { 
						//document.getElementById('button_borrar').disabled = true; 
					}
				}
		}
	});	
	function buscar(){	
			Ext.MessageBox.prompt('<?=Title_busqueda; ?>', '<?=TITLE_AUX_08; ?>', function(btn,text){
				if(btn === 'ok'){
					if(text=="")text="todos";
					storegrid.load({params:{buscar:text}});											
				}
			});
	}	
function agregarnuevouser(){
		var store_paises= new Ext.data.JsonStore({  
			url:'paises_store.php',  
			root: 'data',  
			totalProperty: 'total',  
			fields: [  
				{name:'Idmenu', type: 'string'},  
				{name:'Nombremenu', type: 'string'}
			]  
		});
		store_paises.load();
		
		Ext.apply(Ext.form.VTypes,{
				uppercase:function(val,field) {      
						var texto = val;
						texto = Ext.util.Format.uppercase(texto);
						field.setRawValue(texto);
						return true;          
						  },
				password : function(val, field) {
					if (field.initialPassField) {
						var pwd = Ext.getCmp(field.initialPassField);
						return (val == pwd.getValue());
					}
					return true;
				},
				passwordText : 'Contraseñas no coinciden',
				passwordval  : function(val,field){
					var regx = /^[A-Z]{1}[¡!#$%&()=¿?+*A-Za-zÑñ0-9]*[¡!#$%&()=¿?+*]+[¡!#$%&()=¿?+*A-Za-zÑñ0-9]*$/;
					if (!regx.test(val)){ return false;}	else { return true;}
				}, 
				passwordvalText: 'La nueva clave no cumple con las reglas:' +
                       '<ol><li>La primera letra debe ser mayúscula (A-Z).</li>' +
                       '<li>Debe contener al menos 1 de los siguientes caracteres especiales ¡!#$%&()=¿?+* .</li></ol>'
		});
		var store_perfiles= new Ext.data.JsonStore({  
			url:'perfiles_store.php',  
			root: 'data',  
			totalProperty: 'total',  
			fields: [  
				{name:'Idmenu', type: 'string'},  
				{name:'Nombremenu', type: 'string'}
			]  
		});
		store_perfiles.load();
	var tabs = new Ext.FormPanel({
			labelWidth: 75,
			labelAlign: 'top',
			border:false,
			defaults:{autoHeight:true, bodyStyle:'padding:10px'}, 
			width: 400,
			items:[
				{
				xtype:'tabpanel',
				activeTab: 0,
				//defaults:{autoHeight:true, bodyStyle:'padding:10px'}, 
				border: false,
				items: [
				{
						title:'<?=TITLE_MACE_54?>',
						border: false,
						items:[
							{
										layout:'column',
										border: false,
										items:[
												{
													columnWidth:0.75,
													layout:'form',
													labelAlign: 'left',
													border: false,
													items: [
															{
																	xtype      : 'checkbox',
																	labelStyle: 'font-size:10px;',
																	name: 'tel',
																	width: 80,
																	hidden:true,
																	inputValue : 'a'
															}
														]
												},
												{
													columnWidth:0.25,
													layout:'form',
													labelAlign: 'right',
													border: false,
													items: [
																{
																	xtype      : 'checkbox',
																	fieldLabel: '<b><?=TITLE_MALUM_26?><font color="#EC9001">*</font></b>',
																	labelStyle: 'font-size:10px;',
																	name: 'tel',
																	width: 80,
																	inputValue : 'a',
																	checked:true
																}
														]
												}
										]
							},
							{
								layout:'column',
								border: false,
								items:[
									{
										columnWidth:.50,
										layout:'form',
										border: false,
										items: [
											{
												xtype: 'textfield',
												fieldLabel: '<b><?=TITLE_MALUM_20?><font color="#EC9001">*</font></b>',
												labelStyle: 'font-size:10px;',
												name: 'nombre',
												vtype:'uppercase',
												allowBlank:false,
												width: 190
											}
										]
									},
									{
										columnWidth:.25,
										layout:'form',
										border: false
									},
									{
										columnWidth:.25,
										layout:'form',
										border: false
									}
								]//Fin de las columnas
							},//Fin de Fila 1
							{
								layout:'form',
								border: false,
								items: [
									{
										xtype: 'textfield',
										fieldLabel: '<b><?=TITLE_MALUM_21?><font color="#EC9001">*</font></b>',
										labelStyle: 'font-size:10px;',
										name: 'direccion',
										allowBlank:false,
										width: 413
									},
									{
										xtype: 'textfield',
										fieldLabel: '<b><?=TITLE_MALUM_22?><font color="#EC9001">*</font></b>',
										labelStyle: 'font-size:10px;',
										name: 'director',
										allowBlank:false,
										inputType: 'password',
										id: 'pass',
										vtype: 'passwordval',
										width: 413
									},
									{
										xtype: 'textfield',
										fieldLabel: '<b><?=TITLE_MALUM_23?><font color="#EC9001">*</font></b>',
										labelStyle: 'font-size:10px;',
										name: 'email_director',
										allowBlank:false,
										inputType: 'password',
										vtype: 'password',
										initialPassField: 'pass',
										width: 413
									},
									{
										xtype       : 'combo',
										id          : 'cityCmb',
										fieldLabel  : '<b><?=TITLE_MALUM_24?><font color="#EC9001">*</font></b>',
										labelStyle  : 'font-size:10px;',
										hiddenName  : 'centroId',  
										name        : 'centro_red',  
										loadingText : "Cargando...",
										emptyText   : "Seleccione un perfil...",
										mode        : 'local', 
										allowBlank  : false,
										disabled    : false,
										width       : 250,  
										displayField: 'Nombremenu',  
										valueField  : 'Idmenu',
										store		: store_perfiles
								    },
									{
										xtype       : 'combo',
										id          : 'paisCmb',
										fieldLabel  : '<b>Pais<font color="#EC9001">*</font></b>',
										labelStyle  : 'font-size:10px;',
										hiddenName  : 'paisId',  
										name        : 'centro_red',  
										loadingText : "Cargando...",
										emptyText   : "Seleccione un pais...",
										mode        : 'local', 
										allowBlank  : false,
										disabled    : false,
										width       : 250,  
										displayField: 'Nombremenu',  
										valueField  : 'Idmenu',
										store		: store_paises
								    },
									{
										xtype     : 'datefield',
										fieldLabel: '<b><?=TITLE_MALUM_25?><font color="#EC9001">*</font></b>',
										labelStyle: 'font-size:10px;',
										emptyText:'Dia de vigencia...',  
										format:'Y-m-d', 
										width: 150, 
										name: 'responsableit',
										allowBlank:false
									}
								    
								]
							},//Fin de Seccion de una columna
							{
								layout:'column',
								border: false,
								items:[
									{
										columnWidth:.5,
										layout:'form',
										border: false
									},
									{
										columnWidth:.5,
										layout:'form',
										border: false
									}
								]//Fin de las columnas
							}//Fin de la segunda seccion de 4 columnas
						]
					} 
				]
				}], //Fin del tab
			agregar_form: function(){
				//Primero, se valida si no se estan violando validaciones cliente
				if (this.getForm().isValid()){
					//Empieza el proceso de envio
					this.getForm().submit({
						//Parametros para el envio
						url: 'login_usuarios.php',
						method: 'POST',
						//Mascaras
						waitTitle: 'Conectando',
						waitMsg: 'Validando formulario..',
						//Envio Exitoso
						success: function(form, action){
							Ext.Msg.minWidth = 400;
							Ext.Msg.show({
									   title:'Conexi&oacute;n Exitosa',
									   msg: action.result.msg,
									   buttons: Ext.Msg.OK,
									   icon: Ext.Msg.INFO,
									   fn: function(){
											window_config.close();
											storegrid.removeAll();
											storegrid.load( {params:{idciuddad : action.result.padre, buscar:'todos'}} );
									   }
							});
						},
						//Envio fallido
						failure: function(form, action){
							//Erro data
							if (action.failureType == 'server') {
								var data = Ext.util.JSON.decode(action.response.responseText);
								Ext.Msg.alert('conexi&oacute;n Fallida', data.errors.reason, function(){
									txtUsuario.focus(true, 100);
								});
							}
							//Error archivo
							else {
								Ext.Msg.alert('Error!', 'El servidor de autenticacion es inalcanzable : ' + action.response.responseText);
							}
						}
						
					});
				}
			}
			});
		
		var window_config;
		
		if(!window_config){
		
		window_config= new Ext.Window({
			title: '<?=TITLE_AUX_01?>',
			width: "100%",
			height:500,
			modal: true,
			resizable : false,
			layout: 'fit',
			items: [tabs],
			buttons: [
				{
					text: '<?=Title_agregar?>',
					width: 78,
					handler: function(){
						tabs.agregar_form();
					}
				},
				{
                    text: '<?=Title_limpiar?>',
                    handler: function()
                    {
                        tabs.getForm().reset();
                    }
                 },
				{
					text: '<?=Title_cancelar?>',
					width: 78,
					handler: function(){
						window_config.close();
					}
				}
			]
		});
		
		}
		
		window_config.show();
	}
	//Boton Borrar
	function borrar(){
			Ext.MessageBox.confirm('<?=Title_confirmacion ?>', '<?=PrgAdmin_002?>', function(btn){
				if(btn === 'yes'){
					var selections = gridcentros.selModel.getSelections();
					Ext.each(selections,function(record){
						id = record.get('idcentro');
						storegrid.load({params:{buscar:'todos',proceso:'del',ident:id}});
					});
				}
			});
		};
		
  
		});
		
</script>
  <!-- 	Estilo interno -->
  <style type="text/css">
  body,td,th {
  font-family: Verdana, Geneva, sans-serif;
  }
  </style>
</head>
<body bgcolor="#FFFFFF" leftmargin="0" topmargin="0" marginwidth="0" marginheight="0" >
<div id="grid-div" ></div>
</body>
</html>